# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Maintenance(models.Model):
    """设备维保模型"""
    _name = 'device.maintenance'
    _description = '设备维保管理'
    _order = 'start_date desc, id desc'
    _rec_name = 'display_name'
    _inherit = ['device.permission.mixin']
    
    # 关联设备
    equipment_id = fields.Many2one('device.equipment', '设备', required=True, ondelete='cascade')
    equipment_name = fields.Char('设备名称', related='equipment_id.name', store=True)
    equipment_code = fields.Char('设备编号', related='equipment_id.code', store=True)
    equipment_category = fields.Char('设备类别', related='equipment_id.category_name', store=True)
    equipment_model = fields.Char('设备型号', related='equipment_id.model', store=True)
    
    # 维保信息
    maintenance_pr = fields.Char('维保PR', help='采购申请编号')
    maintenance_po = fields.Char('维保PO', help='采购订单编号')
    contract_number = fields.Char('合同编号')
    contract_amount = fields.Float('合同金额', digits=(16, 2))
    
    # 时间信息
    start_date = fields.Datetime('开始时间', required=True)
    end_date = fields.Datetime('结束时间', required=True)
    
    # 维保状态
    status = fields.Selection([
        ('planned', '计划中'),
        ('ongoing', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消')
    ], string='维保状态', default='planned', required=True)
    
    # 维保类型
    maintenance_type = fields.Selection([
        ('preventive', '预防性维保'),
        ('corrective', '纠正性维保'),
        ('emergency', '紧急维保'),
        ('routine', '例行维保')
    ], string='维保类型', default='routine', required=True)
    
    # 服务商信息
    service_provider = fields.Char('服务商')
    contact_person = fields.Char('联系人')
    contact_phone = fields.Char('联系电话')
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.maintenance')], 
                                   string='相关附件')
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    maintenance_report_url = fields.Char('维保报告URL', help='维保报告文件的URL')
    before_image_urls = fields.Text('维保前图片URL', help='维保前现场图片的URL，多个URL用换行分隔')
    after_image_urls = fields.Text('维保后图片URL', help='维保后现场图片的URL，多个URL用换行分隔')
    invoice_url = fields.Char('发票URL', help='维保费用发票的URL')
    
    # 显示名称
    display_name = fields.Char('显示名称', compute='_compute_display_name', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('equipment_id', 'start_date', 'maintenance_type')
    def _compute_display_name(self):
        for record in self:
            if record.equipment_id and record.start_date:
                record.display_name = f"{record.equipment_id.name} - {record.get_maintenance_type_display()} ({record.start_date.strftime('%Y-%m-%d')})"
            else:
                record.display_name = "新维保记录"
    
    def get_maintenance_type_display(self):
        """获取维保类型显示名称"""
        type_dict = dict(self._fields['maintenance_type'].selection)
        return type_dict.get(self.maintenance_type, self.maintenance_type)
    
    @api.constrains('start_date', 'end_date')
    def _check_dates(self):
        for record in self:
            if record.end_date and record.start_date:
                if record.end_date < record.start_date:
                    raise ValidationError('结束时间不能早于开始时间。')
    
    @api.constrains('contract_amount')
    def _check_contract_amount(self):
        for record in self:
            if record.contract_amount < 0:
                raise ValidationError('合同金额不能为负数。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_start_maintenance(self):
        """开始维保"""
        self.write({'status': 'ongoing'})
    
    def action_complete_maintenance(self):
        """完成维保"""
        self.write({'status': 'completed', 'end_date': fields.Datetime.now()})
    
    def action_cancel_maintenance(self):
        """取消维保"""
        self.write({'status': 'cancelled'})
